package yanivosher.aiproject;

public class Simulator {
	
	public static void simulateWorld()
	{
		Environment env = Environment.getInstance();
		int index = 0;
		while (!env.everyoneInPlace() && index < 5555555) {
			System.out.println("Simulator iteration: " + index);
			for (Agent agent : env.agents) {
				if (!agent.idDone()) {
					Step step = agent.makeAmove(env.graph);
					makeStep(agent,step,env);
				}
				else
				{
					continue;
				}
				if (agent.currentVertex.equals(agent.destinationVertex) && agent.currentVertex.getChem()>0) {
					agent.currentVertex.setChem(0);
				}
				System.out.println("after agent step");
				System.out.println(Environment.getInstance().toString());
			}
			index ++;
		}

		System.out.println("***Agents score:***");
		for (int i = 0; i < env.agents.size(); i++) {
			System.out.println("(" + env.agents.get(i).getClass().getName() +  ")Agent #" + i + ": " + (env.agents.get(i).score)*(env.fCost) + ", " +  env.agents.get(i).explorationCost);
			System.out.println("Steps:");
			for (Step step : env.agents.get(i).stepListForPrint) {
				System.out.println(step);
			}
		}
	}
	
	public static void makeStep(Agent agent , Step step,Environment env){
		agent.stepListForPrint.add(step);
		if (!step.getNoMove() ) {
			
			Vertex stepSrc = env.graph.getVertexById(step.current.getId());
			Vertex stepDest = env.graph.getVertexById(step.destination.getId());
			
			Edge e = env.graph.getEdgeBySourceDestination(stepSrc, stepDest);
			if(e == null)
			{
				Exception e1 = new Exception("Edge in Step cannot be null!!!");
				e1.printStackTrace();
			}
			int cost = e.getWeight();
			
			if (e.getIsBlocked() && step.chem && !step.military) {
				agent.raiseScore(env.hellBreaksLooseCost);
			}
			if (e.getIsBlocked() && step.military && !step.chem) {
				env.graph.removeTerroristFromEdge(stepSrc,stepDest);
			}
			if (step.military) {
				stepSrc.setMilitary(stepSrc.getMilitary() - 1);
				stepDest.setMilitary(stepDest.getMilitary() + 1);
				cost *= 2;
			}
			if (step.chem) {
				stepSrc.setChem(stepSrc.getChem() - 1);
				stepDest.setChem(stepDest.getChem() + 1);
				cost *= 2;
			}
			System.out.println("Moving from " + stepSrc.getId() + " to " + stepDest.getId());
			agent.currentVertex = stepDest;
			agent.raiseScore(cost);
		}
		else
		{
			agent.raiseScore(env.noOpCost);
		}
	}
}
